//
//  SYDSocketViewController.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/8/19.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDSocketViewController.h"
#import "MANaviAnnotation.h"

#import "MovingAnnotationView.h"
#import "TracingPoint.h"
#import "Util.h"

static const NSString *RoutePlanningViewControllerStartTitle       = @"起点";
static const NSString *RoutePlanningViewControllerDestinationTitle = @"终点";

/** define:屏幕的宽高比 */
#define CURRENT_SIZE(_size) _size / 375.0 * SCREEN_WIDTH
@interface SYDSocketViewController ()<MAMapViewDelegate>
{
    CLLocationCoordinate2D coords1[1];
}

@property (nonatomic, strong) MAMapView * mapView;
@property (nonatomic, strong) MAPointAnnotation * car;

/** 轨迹纠偏 */
@property (nonatomic, strong) MATraceManager * traceManager;

/* 起点经纬度. */
@property (nonatomic) CLLocationCoordinate2D                              startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D                              destinationCoordinate;

@property (nonatomic, strong) MAPointAnnotation                         * startAnnotation;
@property (nonatomic, strong) MAPointAnnotation                         * destinationAnnotation;

@property (nonatomic, strong) NSMutableArray *tempTraceLocations;//纠偏数组
@property (strong, nonatomic) NSArray *dataArr;//数据源
@end

@implementation SYDSocketViewController

#pragma mark - 导航栏
- (void)navigationBarHandle{
    
    WEAKSELF
    [weakSelf backButtonAction:^{
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
#pragma mark---Lazy
-(NSMutableArray *)tempTraceLocations{
    if (!_tempTraceLocations) {
        _tempTraceLocations = [NSMutableArray array];
    }
    return _tempTraceLocations;
}
/** 初始化地图 */
-(MAMapView *)mapView{
    if (!_mapView) {
        ///初始化地图
        _mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
        
        _mapView.delegate = self;
        
        ///缩放级别
        _mapView.zoomLevel = 15;
        
        ///是否支持旋转
        _mapView.rotateEnabled = NO;
        
        ///是否支持camera旋转
        _mapView.rotateCameraEnabled = NO;
        
        ///是否显示罗盘
        _mapView.showsCompass = NO;
        
        ///是否显示比例尺
        _mapView.showsScale = NO;
        
        ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
        _mapView.showsUserLocation = NO;  //YES 为打开定位，NO为关闭定位
        //    _mapView.userTrackingMode = MAUserTrackingModeFollow;
        
    }
    return _mapView;
}
-(MATraceManager *)traceManager{
    if (!_traceManager) {
        _traceManager = [[MATraceManager alloc]init];
    }
    return _traceManager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.title = @"轨迹纠偏";
    [self navigationBarHandle];
    //加载数据
    [self addStationAnnotationsAndPolylines];
    ///把地图添加至view
    [self.view addSubview:self.mapView];
    //画轨迹
    [self DrawLine];
    //轨迹纠偏
    [self queryTraceWithLocations:self.tempTraceLocations withSaving:NO];
}
#pragma mark---轨迹和站点标注数据
-(void)addStationAnnotationsAndPolylines{
    NSDictionary *orderData = [NSString resourcePathWithFileName:@"CarpoolDynamics.json"];
    self.dataArr = orderData[@"obj"][@"assistStations"];
    
}
/**绘制路径*/
- (void)DrawLine {

    CLLocationCoordinate2D coords[self.dataArr.count];
    CLLocation *location;
    NSMutableArray * array = [NSMutableArray array];
    for (int i = 0; i < self.dataArr.count; i++) {
        
        NSDictionary *dict= self.dataArr[i];
        if (i==0) {
            coords1[0].latitude = [dict[@"latitude"] doubleValue];
            coords1[0].longitude = [dict[@"longitude"] doubleValue];
        }
        coords[i].latitude = [dict[@"latitude"] doubleValue];
        coords[i].longitude = [dict[@"longitude"] doubleValue];
        
        location = [[CLLocation alloc]initWithLatitude:coords[i].latitude longitude:coords[i].longitude];
        
        [self.tempTraceLocations addObject:location];
        
        [array addObject:location];
    }
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)overlay];
        polylineRenderer.lineWidth    = 6.f;
        [polylineRenderer loadStrokeTextureImage:[UIImage imageNamed:@"arrowTexture"]];
        return polylineRenderer;
        
    }
    
    return nil;
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]]){
        static NSString *pointReuseIndetifier = @"driverReuseIndetifier";
        
        MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        
        if (annotationView == nil){
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:pointReuseIndetifier];
        }
        if (![annotation isKindOfClass:[MANaviAnnotation class]])
        {
            /* 起点. */
            if ([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerStartTitle])
            {
                annotationView.image = [UIImage imageNamed:@"icon_map_start"];
                //设置中心点偏移，使得标注底部中间点成为经纬度对应点
                annotationView.centerOffset = CGPointMake(0, -(CURRENT_SIZE(24)/2));
                
            }
            /* 终点. */
            else if([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerDestinationTitle])
            {
                annotationView.image = [UIImage imageNamed:@"icon_map_end"];
                //设置中心点偏移，使得标注底部中间点成为经纬度对应点
                annotationView.centerOffset = CGPointMake(0, -(CURRENT_SIZE(24)/2));
                
            }
        }
        return annotationView;
    }
    
    
    return nil;
}

#pragma mark -------------------- 轨迹纠偏 --------------------
- (void)queryTraceWithLocations:(NSArray<CLLocation *> *)locations withSaving:(BOOL)saving
{
    NSMutableArray *mArr = [NSMutableArray array];
    for(CLLocation *loc in locations)
    {
        MATraceLocation *tLoc = [[MATraceLocation alloc] init];
        tLoc.loc = loc.coordinate;
        
        tLoc.speed = loc.speed * 3.6; //m/s  转 km/h
        tLoc.time = [loc.timestamp timeIntervalSince1970] * 1000;
        tLoc.angle = loc.course;
        [mArr addObject:tLoc];
    }
    
    __weak typeof(self) weakSelf = self;
    __unused NSOperation *op = [self.traceManager queryProcessedTraceWith:mArr type:-1 processingCallback:nil  finishCallback:^(NSArray<MATracePoint *> *points, double distance) {
        
        NSLog(@"trace query done!");
        [weakSelf addFullTrace:points];
        
        
    } failedCallback:^(int errorCode, NSString *errorDesc) {
        
        NSLog(@"Error: %@", errorDesc);
        //        weakSelf.queryOperation = nil;
    }];
    
}

- (void)addFullTrace:(NSArray<MATracePoint*> *)tracePoints
{
    MAPolyline *polyline = [self makePolylineWith:tracePoints];
    if(!polyline)
    {
        return;
    }
    
    [self.mapView setVisibleMapRect:[polyline boundingMapRect]];
    [self.mapView addOverlay:polyline];
    [self addDefaultAnnotations];
}

- (MAPolyline *)makePolylineWith:(NSArray<MATracePoint*> *)tracePoints
{
    if(tracePoints.count < 2)
    {
        return nil;
    }
    
    CLLocationCoordinate2D *pCoords = malloc(sizeof(CLLocationCoordinate2D) * tracePoints.count);
    if(!pCoords) {
        return nil;
    }
    
    for(int i = 0; i < tracePoints.count; ++i) {
        MATracePoint *p = [tracePoints objectAtIndex:i];
        CLLocationCoordinate2D *pCur = pCoords + i;
        pCur->latitude = p.latitude;
        pCur->longitude = p.longitude;
        
        if(i==0){
            self.startCoordinate = *(pCur);
        }
        if(i == tracePoints.count-1){
            self.destinationCoordinate = *(pCur);
        }
    }
    
    MAPolyline *polyline = [MAPolyline polylineWithCoordinates:pCoords count:tracePoints.count];
    
    if(pCoords)
    {
        free(pCoords);
    }
    
    return polyline;
}

#pragma mark---加载起点终点
- (void) addDefaultAnnotations
{
    MAPointAnnotation *startAnnotation = [[MAPointAnnotation alloc] init];
    startAnnotation.coordinate = self.startCoordinate;
    startAnnotation.title      = (NSString*)RoutePlanningViewControllerStartTitle;
    startAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.startCoordinate.latitude, self.startCoordinate.longitude];
    self.startAnnotation = startAnnotation;
    
    MAPointAnnotation *destinationAnnotation = [[MAPointAnnotation alloc] init];
    destinationAnnotation.coordinate = self.destinationCoordinate;
    destinationAnnotation.title      = (NSString*)RoutePlanningViewControllerDestinationTitle;
    destinationAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.destinationCoordinate.latitude, self.destinationCoordinate.longitude];
    self.destinationAnnotation = destinationAnnotation;
    
    [self.mapView addAnnotation:startAnnotation];
    [self.mapView addAnnotation:destinationAnnotation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}


@end
